package com.cskaoyan.mall.product.runner;

import com.cskaoyan.mall.common.constant.RedisConst;
import com.cskaoyan.mall.product.service.SkuService;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class BloomFilterRunner implements ApplicationRunner {
    @Autowired
    RedissonClient redissonClient;

    @Autowired
    SkuService skuService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //这里是要添加一个布隆过滤器，名字要从哪儿获得，一个配置文件
        long expectedInsertions = 10000;            // 数据规模
        double falseProbability = 0.01;             // 误判率

        //创建布隆过滤器
        RBloomFilter<Long> bloomFilter = redissonClient.getBloomFilter(RedisConst.SKULOCK_SUFFIX);

        //初始化
        bloomFilter.tryInit(expectedInsertions, falseProbability);

        //然后要在其中初始化一下数据
        List<Long> allOnSaleProductsId = skuService.findAllOnSaleProducts();
        for (Long id : allOnSaleProductsId) {
            bloomFilter.add(id);
        }
    }
}
